package game.connection;

import game.GameController;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import com.lloseng.ocsf.client.AbstractClient;

/**
 * Client handles the messages or event from server.
 * 
 * @author Sarun Wongtanakarn 5510546166
 * @author Apiwat Jierakulpanit 5510546212
 * @Version 2013.04.25
 */
public final class GameClient extends AbstractClient implements Observer {

	private Announcer chatBoxAnnouncer;
	private Announcer gameUpdateAnnouncer;
	private final String NAME;

	/** Creates a game client. */
	public GameClient(String host, int port, String name) {
		super(host, port);
		NAME = name;
		initAnnouncer();
	}

	/** Creates the announcer. */
	private void initAnnouncer() {
		chatBoxAnnouncer = new Announcer();
		gameUpdateAnnouncer = new Announcer();
	}

	/** Creates the chat box for this client. */
	private void createChatBox() {
		ChatBox chatBox = new ChatBox("Chat Box");
		chatBox.run();
		chatBoxAnnouncer.addObserver(chatBox);
		chatBox.addObserver(this);
	}

	/**
	 * Prints the message on ChatBox
	 * @param text message to be printed on on ChatBox
	 */
	private void print(String text) {
		chatBoxAnnouncer.announce(text);
	}

	@Override
	protected void handleMessageFromServer(Object arg) {

		if (!(arg instanceof Package)) {
			print("INVALID SERVER");
			return;
		}

		Package pack = (Package) arg;

		if (pack.getType() == PackageType.GAME_INITIATE) {
			print("[Game] START!!");
			GameInitiate game = (GameInitiate) arg;
			GameController gc = new GameController((GameInitiate) arg, this);
			
			gameUpdateAnnouncer.addObserver(gc);
			game.addObserver(gc);
			return;

		} 
		
		if (pack.getType() == PackageType.GAME_EVENT) {
			gameUpdateAnnouncer.announce(arg);
			return;
		}
		
		if (pack.getType() == PackageType.TEXT) {
			print((String) pack.unpack());
			return;
		}

	}

	/** Connects to the server. */
	public void start() {
		createChatBox();
		try {
			this.openConnection();
			this.sendToServer(new Text(NAME));
		} catch (IOException e) {
			print("Server doesn't exist");
			e.printStackTrace();
		}
	}


	@Override
	public void update(Observable o, Object arg) {
		try {
			sendToServer(new Text(arg.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
